﻿using System;
using System.Threading.Tasks;

namespace Ecobee.Net.Demo
{
	public class RequestAuthorizeCommand : CommandBase
	{
		public RequestAuthorizeCommand()
			: base("1", "Request Authorization (PIN)")
		{
		}

		protected async override Task<bool> OnExcute(Api api)
		{
			bool returnValue = false;

			Console.WriteLine("Retrieving authorization...");

			// ***
			// *** Start with an empty token
			// ***
			api.Access.Reset();

			// ***
			// *** Request a PIN number
			// ***
			Authorization authorization = new Authorization(api, AuthorizationScope.SmartWrite);

			// ***
			// *** Request authorization
			// ***
			if (await authorization.GetPinAuthorization())
			{
				Console.WriteLine("Enter the PIN number {0} at www.ecobee.com. Press any key when ready...", authorization.EcobeePin);
				Console.ReadKey();

				if (await api.Access.RequestAccess(authorization))
				{
					Console.WriteLine("Authorization was successful.");
					returnValue = true;
				}
				else
				{
					Console.WriteLine("Request authorization failed.");
				}
			}
			else
			{
				Console.WriteLine("Get Pin Authorization failed.");
			}


			return returnValue;
		}
	}
}
